﻿using System;
using System.Configuration;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Profile;

namespace HttpModules
{
    public class CultureHttpModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
        }

        void context_AuthorizeRequest(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;
            if (app != null && app.User.Identity.IsAuthenticated)
            {
                var profile = ProfileBase.Create(app.User.Identity.Name, true);
                var lang = ((ProfileCommon)profile).Preferences.Culture;
                SetLang(lang);
            }
        }


        void context_BeginRequest(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;
            if (app != null)
            {
                var Request = app.Request;
                var lang = Request["lang"];
                SetLang(lang);
            }
        }

        private static void SetLang(string lang)
        {
            if (string.IsNullOrEmpty(lang)) lang = ConfigurationManager.AppSettings["defaultCulture"];
            //if (string.IsNullOrEmpty(lang))
            //{

            //}
            if (!string.IsNullOrEmpty(lang))
            {
                try
                {
                    var curThread = Thread.CurrentThread;
                    curThread.CurrentUICulture = curThread.CurrentCulture = CultureInfo.GetCultureInfo(lang);
                }
                catch { }
            }
        }
    }
}